package com.eqdd.yiqidian.ui.function.learn

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.LearnLectureListBean
import com.eqdd.yiqidian.bean.rebuild.TeacherListBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.ui.yiqixue.info.LearnTeacherInfoActivity
import com.example.library.AutoFlowLayout
import com.example.library.FlowAdapter
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.fragment_space.view.*
import kotlinx.android.synthetic.main.layout_flow_tag.view.*
import org.jetbrains.anko.support.v4.startActivity

/**
 *
 * Created by jhj on 18-9-21.
 */
class LearnTeacherFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_space, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val status = arguments?.getInt(Config.STATUS)

        if (status == 0 || status == 1) {
            var pageNum = 0
            val mvcHelper = MVCCoolHelper<List<LearnLectureListBean>>(view.coolRefreshView)
            val list = arrayListOf<LearnLectureListBean>()
            view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
            view.recyclerView.layoutManager = LinearLayoutManager(activity)
            val slimAdapterEx = SlimAdapterEx.create()
                    .register<LearnLectureListBean>(R.layout.list_item_192, SlimInjector<LearnLectureListBean> { data, injector ->
                        data?.let {
                            teacher(injector, it.lectureImage, it.lectureName, it.lectureIntroduce, it.lectureType)
                        }

                    })
                    .attachTo(view.recyclerView)
                    .updateData(list as List<*>?) as SlimAdapterEx<LearnLectureListBean>?
            ItemClickSupport.addTo(view.recyclerView)
                    .setOnItemClickListener { recyclerView, position, v ->
                        val bean = slimAdapterEx?.getDataItem(position)
                        startActivity<LearnTeacherInfoActivity>(Config.GUID to (bean?.lectureGuid
                                ?: ""))
                    }

            val dataSource = ModelRx2DataSource<LearnLectureListBean>(ModelRx2DataSource.OnLoadSource<LearnLectureListBean> { page, register ->
                if (page == 1) {
                    pageNum = 0
                }
                OkGo.post<HttpResult<List<LearnLectureListBean>>>(HttpConfig.BASE_URL + HttpConfig.LEARN_TEACHER_RECOMMEND)
                        .params("type", status)
                        .params("page", pageNum)
                        .converter(object : JsonConverter<HttpResult<List<LearnLectureListBean>>>() {
                            override fun test() {
                                super.test()
                            }
                        })
                        .adapt(FlowableBody<HttpResult<List<LearnLectureListBean>>>())
                        .flatMap({ result ->
                            pageNum = result.page
                            Flowable.just(result.items ?: arrayListOf())
                        })
            })

            mvcHelper.setDataSource(dataSource)
            mvcHelper.adapter = slimAdapterEx
            mvcHelper.refresh()
        } else if (status == 2 || status == 3) {
            val url = if (status == 2) {
                HttpConfig.BASE_URL + HttpConfig.LEARN_TEACHER_ACTIVE
            } else {
                HttpConfig.BASE_URL + HttpConfig.LEARN_TEACHER_NEW
            }

            var pageNum = 0
            val mvcHelper = MVCCoolHelper<List<TeacherListBean>>(view.coolRefreshView)
            val list = arrayListOf<TeacherListBean>()
            view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
            view.recyclerView.layoutManager = LinearLayoutManager(activity)
            val slimAdapterEx = SlimAdapterEx.create()
                    .register<TeacherListBean>(R.layout.list_item_192, SlimInjector<TeacherListBean> { data, injector ->
                        data?.let {
                            teacher(injector, it.headimage, it.realname, it.courses, it.researchField)
                            injector?.text(R.id.tv_teacher_price, "￥${it.cooperativePrice}元")
                        }
                    })
                    .attachTo(view.recyclerView)
                    .updateData(list as List<*>?) as SlimAdapterEx<TeacherListBean>?
            ItemClickSupport.addTo(view.recyclerView)
                    .setOnItemClickListener { recyclerView, position, v ->
                        val bean = slimAdapterEx?.getDataItem(position)
                        startActivity<LearnTeacherInfoActivity>(Config.GUID to (bean?.userGuid
                                ?: ""))
                    }

            val dataSource = ModelRx2DataSource<TeacherListBean>(ModelRx2DataSource.OnLoadSource<TeacherListBean> { page, register ->
                if (page == 1) {
                    pageNum = 0
                }
                OkGo.post<HttpResult<List<TeacherListBean>>>(url)
                        .params("page", pageNum)
                        .converter(object : JsonConverter<HttpResult<List<TeacherListBean>>>() {
                            override fun test() {
                                super.test()
                            }
                        })
                        .adapt(FlowableBody<HttpResult<List<TeacherListBean>>>())
                        .flatMap({ result ->
                            pageNum = result.page
                            Flowable.just(result.items ?: arrayListOf())
                        })
            })

            mvcHelper.setDataSource(dataSource)
            mvcHelper.adapter = slimAdapterEx
            mvcHelper.refresh()
        }


    }

    fun teacher(injector: IViewInjector<*>?, img: String, name: String, course: String?, type: String?) {
        injector?.imageCircle(R.id.iv_avatar, img)
                ?.clicked(R.id.iv_avatar) {
                    activity?.imgPathPreview(img)
                }
                ?.text(R.id.tv_name, name)
                ?.with<TextView>(R.id.tv_main_course) {
                    if (!course.isNullOrBlank()) {
                        it.visibility = View.VISIBLE
                        it.text = course
                    } else {
                        it.visibility = View.GONE
                    }
                }
                ?.with<AutoFlowLayout<String>>(R.id.autoFlowLayout) {
                    if (!type.isNullOrBlank()) {
                        it.visibility = View.VISIBLE
                        it.removeAllViews()
                        val split = type?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()
                        it.setAdapter(object : FlowAdapter<String>(split) {
                            override fun getView(p0: Int): View {
                                val view = LayoutInflater.from(activity).inflate(R.layout.layout_flow_tag, null, false)
                                view.tv_tag.text = split?.get(p0)
                                return view
                            }
                        })
                    } else {
                        it.visibility = View.GONE
                    }
                }

    }
}